const Net = require('net')
const logServer = require('./logServer')
const RxFileWrite = require('rxfile-write')

const port = Math.floor(Math.random() * (2000 - 24999 + 1) + 24999)

const pathResolve = require('path').join
const RootPath = pathResolve(__dirname, '../', 'log/')

let filePath = pathResolve( RootPath, '_know_.log')

const logger = Net.createServer(socket => {
  socket.on('data', e => {
    const text = e.toString('utf-8')
    console.log(text)
    RxFileWrite.writeAppendSync(filePath, text)
  })
})

logger.on('error', e=> {
  console.log('日志error', e)
  logger.close()
  console.log('日志服务器启动失败，无法接收信息')
})

logger.listen(port)

logServer(port).then(({e, data}) => {
  // console.log('e=',e)
  // console.log('data=',data)
  if (!(e && e == 'ok')) {
    logger.close()
    console.log(e)
  }

  const name = data.device.deviceid
  const dateStr = Date.now().toString()
  filePath = pathResolve(RootPath, name + '_' + dateStr + '.txt')
  RxFileWrite.writeSync(filePath, dateStr)
  RxFileWrite.writeAppendSync(filePath, '-----------')
}).catch(e => {
  logger.close()
  console.log('失败了e=',e)
})